//
//  HNHandleCourseVC.m
//  优学荟管理系统
//
//  Created by edz on 2018/1/6.
//  Copyright © 2018年 星道三好. All rights reserved.
//

#import "HNHandleCourseVC.h"
#import "HNHandleCourseTeacherCell.h"
#import "HNHandleCourseTeacherModel.h"
#import "TeacherCourseSelectModel.h"
#import "TeacherCourseSelectView.h"
#import "HNHandleCourseSelectAddressView.h"
#import "ZYBigCourseModel.h"
#import "ZYBigCourseTowModel.h"
#import "ZYBigCourseThreeModel.h"
#import "ZYCurriculumMajorCategoryView.h"
#import "ZYLMultiselectView.h"
#import "ZYDatePickerView.h"
#import "HNThreeGoodEvaView.h"
#import "HNHandleCourseThreeGoodView.h"
#import "HMStrongBigCategoryView.h"

@interface HNHandleCourseVC ()<UICollectionViewDelegate, UICollectionViewDataSource, ZYDatePickerViewDelegate, UITextViewDelegate> {
    
    __weak IBOutlet NSLayoutConstraint *bottonSellBtn;
    __weak IBOutlet NSLayoutConstraint *bottonBtnTop;
    __weak IBOutlet NSLayoutConstraint *_gayTwoView;
    __weak IBOutlet NSLayoutConstraint *_gayOneView;
    __weak IBOutlet NSLayoutConstraint *_lessonsBigStrongName;
    __weak IBOutlet NSLayoutConstraint *_lessonsBigName;
    __weak IBOutlet NSLayoutConstraint *_lesssonsName;
    __weak IBOutlet NSLayoutConstraint *_beginClassName;
    __weak IBOutlet NSLayoutConstraint *_beginClassTime;
    __weak IBOutlet NSLayoutConstraint *_overClassTime;
    __weak IBOutlet NSLayoutConstraint *_classHeigh;
    __weak IBOutlet NSLayoutConstraint *_numPeople;
    __weak IBOutlet NSLayoutConstraint *teacherTop;
    __weak IBOutlet UIButton *getLoadBtn;
    __weak IBOutlet UIView *_hideView;
    __weak IBOutlet UIActivityIndicatorView *_activity;
    __weak IBOutlet UIView *_teacherView;
    __weak IBOutlet UICollectionView *_teacherCollectionView;
    __weak IBOutlet UICollectionViewFlowLayout *_teacherCollectionViewFlowLayout;
    __weak IBOutlet NSLayoutConstraint *_teacherCollectionViewHeight;
    __weak IBOutlet NSLayoutConstraint *_teacherViewHeight;
    __weak IBOutlet NSLayoutConstraint *_scrollViewHeight;
    __weak IBOutlet UIView *_scrollView;
    __weak IBOutlet UIView *_threeGoodView;
    __weak IBOutlet NSLayoutConstraint *_threeGoodViewHeight;
    __weak IBOutlet NSLayoutConstraint *_strongCategoryHeight;
    
    __weak IBOutlet NSLayoutConstraint *_threeGoodScrollContant;
    __weak IBOutlet UIButton *_strongCategory;
    __weak IBOutlet UIButton *_bigCourseBtn;
    __weak IBOutlet UIButton *_smallCourseBtn;
    __weak IBOutlet UITextView *_des;
    __weak IBOutlet UILabel *_desPlacehold;
    __weak IBOutlet UIButton *_startCourse;
    __weak IBOutlet UIButton *_endCourse;
    __weak IBOutlet UITextField *_courseName;
    __weak IBOutlet UITextField *_courseTimes;
    __weak IBOutlet UITextField *_maxPeason;
    __weak IBOutlet UITextField *_address;
    __weak IBOutlet UITextField *_price;
    __weak IBOutlet UITextField *_showPrice;
    __weak IBOutlet UIButton *_smallBtn;
    __weak IBOutlet UIButton *_regionBtn;
    __weak IBOutlet UIButton *_commentBtn;
    __weak IBOutlet UIButton *_sellStatusBtn;
    UIButton *_tempButton;
}
@property (nonatomic, strong) NSMutableArray <TeacherCourseSelectModel *>*teacherModels; // 已选中的老师列表
@property (nonatomic, strong) NSMutableArray <TeacherCourseSelectModel *>*notSelectedTeacherModels; // 未选中的老师列表
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSMutableArray *dataSourceTow;
@property (nonatomic, strong) NSMutableArray *dataSourceThree;

@property (nonatomic,copy)NSString *bigID;//大课ID
@property (nonatomic,copy)NSString *commentId;//大课ID
@property (nonatomic, strong) NSArray *regionArr; //省市区
@property (nonatomic, copy) NSString *proviceId;//省id
@property (nonatomic, copy) NSString *cityId;//市id
@property (nonatomic, copy) NSString *areaId;//区id
@property (nonatomic, copy) NSString *smallCategoryIdString;
@property (nonatomic, copy) NSString *sellStatus; // 上下架 上1 下0
@property (nonatomic, strong) NSString *reinforceCategoryId; // 大类目ID



@property (nonatomic, strong) ZYDatePickerView *datePickerView; // 时间选择

@end

@implementation HNHandleCourseVC

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(255, 255, 255)] forBarMetrics:(UIBarMetricsDefault)];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(51,51,51)}];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(255,255,255)}];
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(47, 204, 138)] forBarMetrics:(UIBarMetricsDefault)];
}
//-(void)awakeFromNib
//{
//    [super awakeFromNib];
//    //pand判断少年编程中，编辑状态除了老师view，其他的不可点击
//    if(self.type==HNHandleCourseTypeEdit && self.isProgram){
//
//        _teacherCollectionView.scrollEnabled = NO;
//        _scrollView.origin=CGPointMake(0, 0);
//        _teacherView.origin=CGPointMake(0, 0);
//        for (UIView *view in _scrollView.subviews) {
//
//            if ([view isEqual: _teacherView]||[view isEqual:getLoadBtn]||[view isEqual:_sellStatusBtn]) {
//                view.userInteractionEnabled=YES;
//
//
//                _sellStatusBtn.frame= CGRectMake(0, kScreenHeight-100, kScreenWidth/2, 100);
//                getLoadBtn.frame=CGRectMake(kScreenWidth/2, kScreenHeight-100, kScreenWidth/2, 100);
//            }
//
//            else
//            {
//                //view.userInteractionEnabled=NO;
//                view.hidden=YES;
//            }
//        }
//        // _scrollView.userInteractionEnabled=NO;
//    }
//}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    

    
    _des.layer.cornerRadius = 5.0f;
    _des.layer.masksToBounds = YES;
    _des.layer.borderColor = [ColorRGB(240, 240, 240) CGColor];
    _des.layer.borderWidth = 1.0f;
    
    
    
    self.title = self.type == HNHandleCourseTypeAdd ?  @"添加课程": self.type == HNHandleCourseTypeEdit ? @"编辑课程" : self.type == HNHandleCourseTypeStrongAdd ? @"添加加强课" : @"编辑加强课";
    // 加载加强课UI
    self.type == HNHandleCourseTypeStrongAdd  ? [self strongCourseUI] : nil;
    NSInteger roleCode  = [[AccountTool shareAccountTool].currentAccount.rolecode integerValue];
    if(roleCode==9)
    {
        _threeGoodScrollContant.constant = 50;
      
        CGFloat with = (kScreenWidth - 200)/3;
        for(int i = 0 ; i<2;i++){
            UIButton *strongBtn = [[UIButton alloc]init];
            [_scrollView addSubview:strongBtn];
            [strongBtn setBackgroundImage:[UIImage imageNamed:@"btn_homework_choice_default"] forState:0];
            [strongBtn setFont:[UIFont systemFontOfSize:14]];
            strongBtn.tag = 402 + i;
            [strongBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.offset(with+(100+with)*i);
                make.top.equalTo(_threeGoodView.mas_top).offset(-38);
                make.width.offset(100);
                make.height.offset(30);
            }];
            if(strongBtn.tag==402)
            {
                [strongBtn setTitle:@"加强要素" forState:0];
                [strongBtn addTarget:self action:@selector(strongSelctor:) forControlEvents:UIControlEventTouchUpInside];
            }
            else
            {
                [strongBtn setTitle:@"加强知识点" forState:0];
                [strongBtn addTarget:self action:@selector(strongSelctor:) forControlEvents:UIControlEventTouchUpInside];
            }
        }
        
    }
    else
    {
       _threeGoodScrollContant.constant = 16;
    }
   
    // 编辑普通课数据
    self.type == HNHandleCourseTypeEdit || self.type == HNHandleCourseTypeStrongEdit? [self RefreshUploadDataWithSucces:^(id obj) {
        
        [self editingUI:obj];
    }] : nil;
    // 是否加载加强课类目
    _strongCategoryHeight.constant = self.type == HNHandleCourseTypeAdd || self.type == HNHandleCourseTypeEdit ? 0 : 45;
    _scrollViewHeight.constant -= self.type == HNHandleCourseTypeAdd || self.type == HNHandleCourseTypeEdit ? 45 : 0;
    
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTargat:self action:@selector(Pop) image:@"icon_back_student_sign" highImage:@"icon_back_student_sign"];
    
    //  预加载地区文件
    [HNHandleCourseSelectAddressView regionArr:^(NSArray *Arr) {
        
        self.regionArr = Arr;
    }];
    
    // 给老师的collection加一个对象
    [self addIsLastObject];
    

    // teacher collectionView config
    _teacherCollectionViewFlowLayout.minimumLineSpacing = 8;
    _teacherCollectionViewFlowLayout.minimumInteritemSpacing = 8;
    _teacherCollectionViewFlowLayout.sectionInset = UIEdgeInsetsMake(8, 8, 8, 8);
    [_teacherCollectionView registerNib:[UINib nibWithNibName:[HNHandleCourseTeacherCell description] bundle:nil] forCellWithReuseIdentifier:@"Cell"];
    [self completeCollectionViewHeight];
    
    
    // 先获取老师的信息
    [self RefreshDataWithTeacher:^(NSArray<TeacherCourseSelectModel *> *Arr) {
       
        
        [self setNetWork];
        self.notSelectedTeacherModels = [Arr mutableCopy];
        [_teacherCollectionView reloadData];
    }];
    

    
    // 防止双小数点
    [_price addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    [_showPrice addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    
    //pand判断少年编程中，编辑状态除了老师view，其他的不可点击
    if(self.type==HNHandleCourseTypeEdit && self.isProgram){

        
        for (UIView *view in _scrollView.subviews) {
            _scrollViewHeight.constant=kScreenHeight-64;
            _gayOneView.constant=0;
            _gayTwoView.constant=0;
            _lessonsBigStrongName.constant=0;
            _lessonsBigName.constant=0;
            _lesssonsName.constant=0;
            _beginClassName.constant=0;
            _beginClassTime.constant=0;
           _overClassTime.constant=0;
            _classHeigh.constant=0;
           _numPeople.constant=0;
            bottonSellBtn.constant=kARHeightTranslator(85);
            bottonBtnTop.constant=kARHeightTranslator(85);
            if ([view isEqual: _teacherView]||[view isEqual:getLoadBtn]||[view isEqual:_sellStatusBtn]) {
                view.userInteractionEnabled=YES;
                
            }
            
            else
            {
                //[view removeFromSuperview];
                //view.userInteractionEnabled=NO;
                view.hidden=YES;
            }
        }
      
    }
}
-(void)strongSelctor:(UIButton *)sender
{
    
}
#pragma mark - 网络请求
/** 获取网络的课程数据 */
- (void)RefreshUploadDataWithSucces:(void (^)(id obj))Succes {
    
    NSDictionary *params = @{
                             @"action"  :@"getLessonById2",
                             @"id"      :self.Id
                             };
    [NetManager Get:LLBaseURL(@"lesson.do") Auth:YES Params:params Success:^(id Obj) {
        
        
        if ([Obj[@"code"] isEqualToNumber:@1000]) {
            // 成功回调
            Succes (Obj);
            [_hideView removeFromSuperview];
        } else {
            
            [_activity stopAnimating];
            [HUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        
        [HUD showError:NetErr];
        [_activity stopAnimating];
    }];
}

- (void)RefreshDataWithTeacher:(void (^)(NSArray <TeacherCourseSelectModel *>*Arr))Complete {
    
    [MBProgressHUD showHUD];
    NSDictionary *Params = @{
                             @"action":@"getTeacherByOid",
                             @"oid":[AccountTool shareAccountTool].currentAccount.oid
                             };
    [NetManager Get:LLBaseURL(@"lesson.do") Auth:YES Params:Params Success:^(id Obj) {
        
        if ([Obj[@"code"] isEqualToNumber:@1000]) {
            
            NSMutableArray *MutableArr = [NSMutableArray array];
            [Obj[@"t"] enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                [MutableArr addObject:[TeacherCourseSelectModel HNObjectValuesForKey:obj]];
            }];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                Complete ? Complete ([MutableArr copy]) : nil ;
                [_hideView removeFromSuperview];
            });
            
            
        } else {
            [MBProgressHUD showError:Obj[@"msg"]];
            [_activity stopAnimating];
        }
        
    } Fail:^(NSError *Error) {
        [MBProgressHUD showError:NetErr];
        [_activity stopAnimating];
    }];
}

// 大类目接口
- (void)setNetWork{
    // http://192.168.0.113:8080/StarShine/ys/lesson.do?action=getBigCategory
    NSString *url = [NSString stringWithFormat:@"lesson.do?action=getBigCategory"];
    
    
    NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    
    [MBProgressHUD showHUD];
    
    [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
        [self.dataSource removeAllObjects];
        [MBProgressHUD hideHUD];
        if ([[Obj valueForKey:@"code"] integerValue] == 1000) {
            
            NSArray *arr = [Obj valueForKey:@"t"];
            
            for (NSDictionary *dict  in arr) {
                ZYBigCourseModel *model = [ZYBigCourseModel new];
                model.ID = [dict valueForKey:@"id"];
                [model setValuesForKeysWithDictionary:dict];
                [self.dataSource addObject:model];
            }
        }
        
    } Fail:^(NSError *Error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:NetErr];
    }];
    
}

// 小类目接口
- (void)setNetWorkTow:(UITextField *)textField{
    
    NSString *url = [NSString stringWithFormat:@"lesson.do?action=getSmallCategoryByBigId&bigId=%@",self.bigID];
    
    NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    [MBProgressHUD showHUD];
    [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
        [self.dataSourceTow removeAllObjects];
        [MBProgressHUD hideHUD];
        if ([[Obj valueForKey:@"code"] integerValue] == 1000) {
            
            NSArray *arr = [Obj valueForKey:@"t"];
            
            for (NSDictionary *dict  in arr) {
                ZYBigCourseTowModel *model = [ZYBigCourseTowModel new];
                model.ID = [dict valueForKey:@"id"];
                [model setValuesForKeysWithDictionary:dict];
                [self.dataSourceTow addObject:model];
                
            }
        }
        
        
        
    } Fail:^(NSError *Error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:NetErr];
    }];
}

/** 评价模板 */
- (void)setNetWorkThree:(UIButton *)sender {
    NSString *url = [NSString stringWithFormat:@"lesson.do?action=getTemplates"];
    
    
    NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    [MBProgressHUD showHUD];
    [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
        [self.dataSourceThree removeAllObjects];
        [MBProgressHUD hideHUD];
        if ([[Obj valueForKey:@"code"] integerValue] == 1000) {
            
            NSDictionary *t = [Obj valueForKey:@"t"];
            
            
            NSArray *arr = [t  valueForKey:@"dataList"];
            
            for (NSDictionary *dict  in arr) {
                ZYBigCourseThreeModel *model = [ZYBigCourseThreeModel new];
                model.ID = [dict valueForKey:@"id"];
                [model setValuesForKeysWithDictionary:dict];
                [self.dataSourceThree addObject:model];
            }
            
            if (self.dataSourceThree.count != 0) {
                [self curriculumThree:sender];
            }else{
                self.commentId = @"0";
                [self createAlertViewWithTitle:nil message:@"没有数据" preferredStyle:(UIAlertControllerStyleAlert) disapperaTime:1 andDis:nil];
            }
            
            
        }
        
        
        
        
    } Fail:^(NSError *Error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:NetErr];
    }];
    
    
 
    
}

#pragma mark - teacher collectionView delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.teacherModels.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    TeacherCourseSelectModel *model = self.teacherModels[indexPath.item];
    HNHandleCourseTeacherCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
   
    cell.model = model;
    //是否隐藏删除按钮
    cell.LongPressAction = ^(BOOL isHideDelete) {
        [self handleDeleteImg:isHideDelete];
    };
    // 删除老师
    cell.deleteTeacherAction = ^(TeacherCourseSelectModel *model) {
        [self handleDeleteTeacher:model];
    };
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    TeacherCourseSelectModel *model = self.teacherModels[indexPath.item];
    
    // 删除按钮隐藏了就正常走流程
    if (model.isLastObject) {
        
        // 添加
        [self addTeacher];
    } else {

        // 选中老师code
        
        
    }
}

#pragma mark - func
- (BOOL)MBProgressWithTextField:(NSString *)text msg:(NSString *)msg {
     text = [NSString stringWithFormat:@"%@",text];
    
    if ([msg isEqualToString:@"请输入售价"]==YES||[msg isEqualToString:@"请输入原价"]==YES) {
   
    }
    else
    {
       text = [text isEqualToString:@"0"] ? @"":text;
    }
    
    if ([text stringByReplacingOccurrencesOfString:@" " withString:@""].length <= 0) {
        
        [MBProgressHUD showError:msg];
        return NO;
    }
    return YES;
}
/** 计算高度 */
- (void)completeCollectionViewHeight {
    
    CGFloat x = kScreenWidth - _teacherCollectionView.frame.origin.x - 15;
    CGFloat w = (x - 8 * 4) / 3;
    CGFloat h = w *(5.00 / 8.00);
    _teacherViewHeight.constant -= _teacherCollectionViewHeight.constant;
    _scrollViewHeight.constant -= _teacherCollectionViewHeight.constant;
    NSInteger integer = self.teacherModels.count / 3;
    CGFloat f = self.teacherModels.count / 3.0;
    integer = f > integer ? integer + 1 : integer;
    _teacherCollectionViewHeight.constant = (integer * h) + (integer * 8 + 8);
    _teacherViewHeight.constant += _teacherCollectionViewHeight.constant;
    _scrollViewHeight.constant += _teacherCollectionViewHeight.constant;
    _teacherCollectionViewFlowLayout.itemSize = CGSizeMake(w, h);
    [UIView animateWithDuration:0.3 animations:^{
        [self.view layoutIfNeeded];
    }];
}

/** 给已选中的列表增加一个添加操作 */
- (void)addIsLastObject {
    
    TeacherCourseSelectModel *model = [[TeacherCourseSelectModel alloc] init];
    model.isLastObject = YES;
    model.uid = @1112323.111111;
    model.petName = @"";
    [self.teacherModels addObject:model];
}

/** 处理删除按钮的显示隐藏状态 */
- (void)handleDeleteImg:(BOOL)isHideDelete {
    
    isHideDelete = !isHideDelete;
    [self.teacherModels enumerateObjectsUsingBlock:^(TeacherCourseSelectModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.isHideDeleteImg = obj.isLastObject ? YES : isHideDelete;
    }];
    // 根据状态增加或移除添加按钮
    isHideDelete ? [self addIsLastObject] : [self.teacherModels removeLastObject];
    [_teacherCollectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
    
    // 更新下高度
    [self completeCollectionViewHeight];
}

/** 处理删除老师的操作 */
- (void)handleDeleteTeacher:(TeacherCourseSelectModel *)model {
    
    NSInteger index = [self.teacherModels indexOfObject:model];
    [self.teacherModels removeObject:model];
    [_teacherCollectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];

    // 没有数据也要加一个
    if (self.teacherModels.count == 0) {
        
        [self handleDeleteImg:NO];
    } else {
        
        // 更新下高度
        [self completeCollectionViewHeight];
    }

}

//比较两个日期的大小  日期格式为2016-08-14 08：46：20
- (NSInteger)compareDate:(NSString*)starTimer withDate:(NSString*)finishTimer
{
    
    // 相等
    BOOL result = [starTimer compare:finishTimer] == NSOrderedSame;
    if (result == 1) {
        return 0;
    }
    
    // a > b
    BOOL result1 = [starTimer compare:finishTimer] == NSOrderedDescending;
    if (result1 == 1) {
        return -1;
    }
    
    // a < b;
    BOOL result2 = [starTimer compare:finishTimer] == NSOrderedAscending;
    if (result2 == 1) {
        return 1;
    }
    
    return 0;
}

- (void)textViewDidChange:(UITextView *)textView {
    
    _desPlacehold.hidden = textView.text.length;
}

- (void)textFieldDidChange:(UITextField *)textField {
    
    if ([textField.text isEqualToString:@"."]) {
        
        textField.text = @"0.";
    }
    
    NSArray *arr = [textField.text componentsSeparatedByString:@"."];
    if (arr.count > 2) {
        
        textField.text = [textField.text substringToIndex:[textField.text length] - 1];
    }
    
    NSString *str = [arr lastObject];
    if (arr.count > 1 && [str length] > 2) {
        
        
        textField.text = [NSString stringWithFormat:@"%@.%@",[arr firstObject], [str substringToIndex:2]];
    }
}

#pragma mark - click action
- (void)Pop {
    
    [self.navigationController popViewControllerAnimated:YES];
}
     
/** 添加老师 */
- (void)addTeacher {
    

    NSMutableArray *TitleArr = [NSMutableArray array];
    NSMutableArray *uidArr = [NSMutableArray array];
    // 剔出已选中的老师不显示
    [self.notSelectedTeacherModels enumerateObjectsUsingBlock:^(TeacherCourseSelectModel * _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
        
        __block BOOL isExist = NO;
        [self.teacherModels enumerateObjectsUsingBlock:^(TeacherCourseSelectModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            // 相等就直接退出吧
            *stop = isExist = [model.uid isEqualToNumber:obj.uid] ? YES:NO;
        }];
        // 不存在的话才显示
        isExist ? nil : [TitleArr addObject:model.petName];
        isExist ? nil : [uidArr addObject:model.uid];
    }];
    
    // 弹窗并选择老师
    TeacherCourseSelectView *View = [TeacherCourseSelectView ConfigWithArr:[TitleArr copy] Complete:^(NSInteger Index) {
        
        // 最末尾元素的下标
        NSInteger index = self.teacherModels.count - 1;
        [self.notSelectedTeacherModels enumerateObjectsUsingBlock:^(TeacherCourseSelectModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.uid isEqualToNumber:uidArr[Index]]) {
                
                // 插入到添加item的前面
                [self.teacherModels insertObject:[obj copy] atIndex:index];
                // 更新下collectionView
                [_teacherCollectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
                // 更新下高度
                [self completeCollectionViewHeight];
                *stop = YES;
            }
        }];
        
    }];
    View.Title.text = @"请选择课程老师";
}

/** 选择加强课大类目 */
- (IBAction)selectStrongCategory:(UIButton *)sender {
    
    HMStrongBigCategoryView *view = [[[NSBundle mainBundle]loadNibNamed:@"HMStrongBigCategoryView" owner:nil options:nil]lastObject];
    view.frame = [UIApplication sharedApplication].keyWindow.bounds;
    [[UIApplication sharedApplication].keyWindow addSubview:view];
    __block typeof(self) weakSelf  = self;
    view.selectRowBlock = ^(HMStrongBigCategoryModel *model) {

        [_strongCategory setTitle:model.categoryName forState:_strongCategory.state];
        weakSelf.reinforceCategoryId = model.Id;
    };
}

/** 选择上课地点 */
- (IBAction)selectAddress:(UIButton *)sender {
    
    [self.view endEditing:YES];
    [HNHandleCourseSelectAddressView handleCourseSelectAddressViewWithRegionArr:self.regionArr CallBack:^(NSString *province, NSNumber *provinceId, NSString *city, NSNumber *cityId, NSString *distric, NSNumber *districId, NSString *address, NSString *addressId) {
        
        _proviceId = [provinceId stringValue];
        _cityId = [cityId stringValue];
        _areaId = [districId stringValue];
        [sender setTitle:address forState:sender.state];
    }];
}

/** 大类目选择 */
- (IBAction)selectBigCategory:(UIButton *)sender {
    
    [self.view endEditing:YES];
    [ZYCurriculumMajorCategoryView showWithTitle:@"请选择课程大类目" titles:self.dataSource zYBigCourseModel:nil zYBigCourseTowModel:nil zYBigCourseThreeModel:nil selectIndex:^(NSInteger selectIndex) {
        
        
        
        self.bigID = [NSString stringWithFormat:@"%ld",(long)selectIndex];
        self.smallCategoryIdString = @"";
        [_smallBtn setTitle:@"请选择课程小类目(多选)" forState:_smallBtn.state];
        [self setNetWorkTow:nil];
        
        
    } selectValue:^(NSString *selectValue) {
        
        [sender setTitle:selectValue forState:sender.state];
        
    } showCloseButton:NO isUp:NO isUpAll:NO];
}

/** 小类目选择 */                              
- (IBAction)selectSmallCategory:(UIButton *)sender {
    
    [self.view endEditing:YES];
    [self setNetWorkTow:nil];

    ZYLMultiselectView *zyl = [[ZYLMultiselectView alloc]initWithFrame:CGRectMake(30, 50, kScreenWidth - 60, kScreenHeight - 150)];
    zyl.dataSource = self.dataSourceTow;
    
    [self.view addSubview:zyl];
    
    
    zyl.selectBlock = ^(NSMutableArray *selectUserId,NSMutableArray *name) {

        NSString *Str = [name componentsJoinedByString:@","];
        [sender setTitle:Str forState:sender.state];
        self.smallCategoryIdString = [selectUserId componentsJoinedByString:@","];
    };
}

/** 开课时间 */
- (IBAction)startCourse:(UIButton *)sender {
    [self.view endEditing:YES];
    _tempButton = sender;
    
    self.datePickerView.title = @"开课时间";
    [self.datePickerView show];
}

/** 结束时间 */
- (IBAction)endCourse:(UIButton *)sender {
    [self.view endEditing:YES];
    _tempButton = sender;
    
    self.datePickerView.title = @"结课时间";
    [self.datePickerView show];
}

//当时间改变时触发
- (void)changeTime:(NSDate *)date{
    // NSLog(@"代理监听更改时间为---%@",[self.datePickerView stringFromDate:date]);
}

//确定时间
- (void)determine:(NSDate *)date{
    
    NSString *timeStr = [NSString stringWithFormat:@"%@:%@",[self.datePickerView stringFromDate:date],@"00"];
    
    if ( _startCourse == _tempButton) {
    
        // 0 相等 1B>A -1B<A
        NSString *time = [_endCourse.currentTitle isEqualToString:@"请选择"] ? @"2050-12-12 12:12:12":_endCourse.currentTitle;
        [self compareDate:timeStr withDate:time] == 1 ? [_startCourse setTitle:timeStr forState:_startCourse.state] : [self createAlertViewWithTitle:@"课程结束时间必须大于课程开始时间" message:nil preferredStyle:(UIAlertControllerStyleAlert) disapperaTime:1.2 andDis:nil];
        
        
    }
    
    if (_endCourse == _tempButton){
        // 0 相等 1B>A -1B<A
        NSString *time = [_startCourse.currentTitle isEqualToString:@"请选择"] ? @"2008-12-12 12:12:12":_startCourse.currentTitle;
        [self compareDate:time withDate:timeStr] == 1 ? [_endCourse setTitle:timeStr forState:_endCourse.state] : [self createAlertViewWithTitle:@"课程结束时间必须大于课程开始时间" message:nil preferredStyle:(UIAlertControllerStyleAlert) disapperaTime:1.2 andDis:nil];
    }
    
}

/** 评论模板 */
- (IBAction)selectComment:(UIButton *)sender {
    [self.view endEditing:YES];
    [self setNetWorkThree:sender];
}

/** 评论模板2 */
- (void)curriculumThree:(UIButton *)sender {
    [ZYCurriculumMajorCategoryView showWithTitle:@"请选择评价模板" titles:self.dataSourceThree zYBigCourseModel:nil zYBigCourseTowModel:nil zYBigCourseThreeModel:nil selectIndex:^(NSInteger selectIndex) {

        self.commentId = [NSString stringWithFormat:@"%ld",(long)selectIndex];
    } selectValue:^(NSString *selectValue) {
        
        [sender setTitle:selectValue forState:(sender.state)];
        
    } showCloseButton:NO  isUp:NO isUpAll:YES];
}

/** 更改状态 */                              
- (IBAction)sellStatusDidChange:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    self.sellStatus = sender.selected ? @"0":@"1";
    
    
        NSString *url = @"trainLesson.do?action=getDynamicEvaluation&type=2&pageNumber=1";
        [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleCustom)];
        [SVProgressHUD  setBackgroundColor:ColorRGB(4, 4, 4)];
        [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
        [SVProgressHUD showWithStatus:LLLoading];
        NSLog(@"%@  %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
        NSDictionary *Params = @{@"action" :@"changeSellStatus",
                                 @"id":self.Id,@"sellStatus":self.sellStatus};
        
        [NetManager Get:LLBaseURL(@"lesson.do") Auth:YES Params:Params Success:^(id Obj) {
            if ([Obj[@"code"] isEqualToNumber:@1000]) {
                [SVProgressHUD showSuccessWithStatus:@"操作成功!"];
               
                
            }else {
                [SVProgressHUD showErrorWithStatus:Obj[@"msg"]];
                
            }
        } Fail:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:NetErr];
           
        }];
    

   
    
}

/** 确定 */
- (IBAction)sure:(UIButton *)sender {
    
    
    //http://192.168.0.113:8080/StarShine/ys/lesson.do?action=updateCapacityLesson&lessonId=&uids=

    
    // 找出所有的老师
    NSMutableArray *arr = [self.teacherModels mutableCopy];
    [arr removeLastObject];
    NSMutableArray *uids = [NSMutableArray array];
    [arr enumerateObjectsUsingBlock:^(TeacherCourseSelectModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [uids addObject:obj.uid];
    }];
    NSString *uidsStr = [uids componentsJoinedByString:@","];
    if (uids.count <= 0) {
        
        [MBProgressHUD showError:@"请选择上课老师"]; return;
    }
    
    
    NSDictionary *dic = @{@"lessonId":self.Id ? self.Id : @"" ,@"uids":uidsStr ? uidsStr : @"",@"action":@"updateCapacityLesson",@"sellStatus":self.sellStatus ? self.sellStatus : @"1"};
    
    if (_isProgram) {
        [NetManager Post:LLBaseURL(@"lesson.do") Auth:YES Params:dic Success:^(id Obj) {
            
            if ([Obj[@"code"] isEqualToNumber:@1000]) {
                
                [MBProgressHUD showSuccess:@"操作成功!"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    // 只增加才弄刷新
                    self.PopOfRefresh ? self.PopOfRefresh() : nil;
                    [self.navigationController popViewControllerAnimated:YES];
                });
                
            } else {
                
                [MBProgressHUD showError:Obj[@"msg"]];
            }
        } Fail:^(NSError *Error) {
            [MBProgressHUD showError:NetErr];
        }];
    }
    else
    {
    
    
    // 找出所有加强要素
    NSMutableArray *threeGoods = [NSMutableArray array];
    [self.strongDatas enumerateObjectsUsingBlock:^(HNCourseListChartsModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.selected == YES ? [threeGoods addObject:obj.ID] : nil;
    }];
    
    if (self.type == HNHandleCourseTypeStrongEdit || self.type == HNHandleCourseTypeStrongAdd) {

        if (![self MBProgressWithTextField:self.reinforceCategoryId msg:@"请选择加强课大类目"]) {
        
            return;
        }
    }
    
        if (![self MBProgressWithTextField:self.bigID msg:@"请选择大类目"]) {
        
            return;
        }
    

    if ([_startCourse.currentTitle isEqualToString:@"请选择"] ||
        [_endCourse.currentTitle isEqualToString:@"请选择"] ||
        [_commentBtn.currentTitle isEqualToString:@"请选择"] ||
        [_regionBtn.currentTitle isEqualToString:@"请选择"] ) {
        [MBProgressHUD showError:@"请完善选择项"]; return;
    }
    
    
    
    if (![self MBProgressWithTextField:_courseName.text msg:@"请输入课程名称"]) {
        return;
    }
    
    if (![self MBProgressWithTextField:_courseTimes.text msg:@"请输入课时"]) {
        return;
    }
    
//    if (![self MBProgressWithTextField:_maxPeason.text msg:@"请输入报名上限人数"]) {
//        return;
//    }
    
    if (![self MBProgressWithTextField:_address.text msg:@"请输入街道地址"]) {
        return;
    }
    
    if (![self MBProgressWithTextField:[NSString stringWithFormat:@"%@", _price.text] msg:@"请输入售价"]) {
        return;
    }
    
    if (![self MBProgressWithTextField:[NSString stringWithFormat:@"%@", _showPrice.text] msg:@"请输入原价"]) {
        return;
    }
    
    if (![self MBProgressWithTextField:_des.text msg:@"请输入课程简介"]) {
        return;
    }
    
    if (self.type == HNHandleCourseTypeStrongAdd) {
        
        if (threeGoods.count < 1) {
            
            [MBProgressHUD showError:@"请至少选择一个三好要素"];
            return;
        }
    }
    
    
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    [params setValue:self.sellStatus forKey:@"sellStatus"];
        [params setValue:_maxPeason.text.length==0 ? @"10000" : _maxPeason.text forKey:@"limitNum"];
    [params setValue:self.areaId forKey:@"areaid"];
    [params setValue:_showPrice.text forKey:@"showPrice"];
    [params setValue:self.proviceId forKey:@"provinceid"];
    [params setValue:self.type == HNHandleCourseTypeAdd || self.type == HNHandleCourseTypeEdit ? @"2":@"10" forKey:@"type"];
    [params setValue:_endCourse.currentTitle forKey:@"endTime"];
    [params setValue:self.smallCategoryIdString forKey:@"smallCategoryIdString"];
    [params setValue:self.cityId forKey:@"cityid"];
    [params setValue:self.bigID forKey:@"courseCategoryId"];
    [params setValue:_startCourse.currentTitle forKey:@"startTime"];
    [params setValue:self.commentId forKey:@"templateId"];
    [params setValue:@"" forKey:@"classroom"];
    [params setValue:_price.text forKey:@"price"];
    [params setValue:@"0" forKey:@"coins"];
    [params setValue:_address.text forKey:@"address"];
    [params setValue:@"" forKey:@"lessonTime"];
    [params setValue:_des.text forKey:@"description"];
    [params setValue:_courseName.text forKey:@"name"];
    [params setValue:_courseTimes.text forKey:@"courseCount"];
    [params setValue:self.type == HNHandleCourseTypeAdd || self.type == HNHandleCourseTypeStrongAdd ? @"saveLessonMoreTea":@"updateLesson2" forKey:@"action"];
    [params setValue:uidsStr forKey:@"uids"];
    
    self.type == HNHandleCourseTypeEdit || self.type == HNHandleCourseTypeStrongEdit ? [params setValue:[self.Id stringValue] forKey:@"id"] : nil;
    self.type == HNHandleCourseTypeStrongAdd || self.type == HNHandleCourseTypeStrongEdit ? [params setValue:[threeGoods componentsJoinedByString:@""] forKey:@"elementIds"]:nil;
    self.type == HNHandleCourseTypeStrongAdd ? [params setValue:self.Id forKey:@"commonLessonId"]:nil;
    self.type == HNHandleCourseTypeStrongAdd || self.type == HNHandleCourseTypeStrongEdit ? [params setValue:self.reinforceCategoryId forKey:@"reinforceCategoryId"] : nil;
    
  

   
        [NetManager Post:LLBaseURL(@"lesson.do") Auth:YES Params:params Success:^(id Obj) {
            
            if ([Obj[@"code"] isEqualToNumber:@1000]) {
                
                [MBProgressHUD showSuccess:@"操作成功!"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    // 只增加才弄刷新
                    self.PopOfRefresh ? self.PopOfRefresh() : nil;
                    [self.navigationController popViewControllerAnimated:YES];
                });
                
            } else {
                
                [MBProgressHUD showError:Obj[@"msg"]];
            }
        } Fail:^(NSError *Error) {
            
            [MBProgressHUD showError:NetErr];
        }];
    
    }
}


#pragma mark - get
- (NSMutableArray <TeacherCourseSelectModel *> *)teacherModels{ if (!_teacherModels) { _teacherModels = [NSMutableArray array]; } return _teacherModels; }
- (NSMutableArray *)dataSource { if (_dataSource == nil) { self.dataSource = [NSMutableArray array]; } return _dataSource;}
- (NSMutableArray *)dataSourceTow { if (_dataSourceTow == nil) { _dataSourceTow = [NSMutableArray array]; } return _dataSourceTow;}
- (NSMutableArray *)dataSourceThree { if (_dataSourceThree == nil) { _dataSourceThree = [NSMutableArray array]; } return _dataSourceThree; }
- (NSString *)sellStatus { if (!_sellStatus) { _sellStatus = @"1"; } return _sellStatus; }
- (ZYDatePickerView *)datePickerView {
    if (_datePickerView == nil) {
        self.datePickerView = [[ZYDatePickerView alloc]initWithFrame:self.view.bounds type:UIDatePickerModeDateAndTime];
        self.datePickerView.delegate = self;
        self.datePickerView.optionalMinDate = [NSDate date];
    }
    return _datePickerView;
}


































#pragma mark - 编辑
// 编辑 UI
- (void)editingUI:(NSDictionary *)dict {
    
    dict = dict[@"t"];
    
    [_strongCategory setTitle:[self JudgeNullClass:dict[@"reinforceCategoryName"]] forState:_strongCategory.state];
    self.reinforceCategoryId = [dict[@"reinforceCategoryId"] stringValue];
    
    //上下架状态
    self.sellStatus = [[self JudgeNullClass:dict[@"sellStatus"]] stringValue];
    _sellStatusBtn.selected = [self.sellStatus isEqualToString:@"1"] ? NO:YES;
    
    // 大类
    [_bigCourseBtn setTitle:[self JudgeNullClass:dict[@"courseCategoryName"]] forState:_bigCourseBtn.state];
    self.bigID = [[self JudgeNullClass:dict[@"courseCategoryId"]] stringValue];
    [self setNetWorkTow:nil];
    
    // 小类
    NSMutableArray *smallTitles = [NSMutableArray array];
    NSMutableArray *smallIds = [NSMutableArray array];
    [[self JudgeNullClass:dict[@"smallIds"]] enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [smallTitles addObject:[self JudgeNullClass:obj[@"categoryName"]]];
        [smallIds addObject:[self JudgeNullClass:obj[@"id"]]];
    }];
    [_smallBtn setTitle:[smallTitles componentsJoinedByString:@","] forState:_smallBtn.state];
    self.smallCategoryIdString = [smallIds componentsJoinedByString:@","];
    
    // 名称
    _courseName.text = [self JudgeNullClass:dict[@"name"]];
    
    // 开课时间、结课时间、课时、报名人数上限
    [_startCourse setTitle:[self JudgeNullClass:dict[@"startTime"]] forState:_startCourse.state];
    [_endCourse setTitle:[self JudgeNullClass:dict[@"endTime"]] forState:_endCourse.state];
    _courseTimes.text = [[self JudgeNullClass:dict[@"courseCount"]] stringValue];
    _maxPeason.text = [[self JudgeNullClass:dict[@"limitNum"]] stringValue];
    
    // 老师
    [self.teacherModels removeAllObjects];
    [[self JudgeNullClass:dict[@"teachers"]] enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       
        TeacherCourseSelectModel *model = [TeacherCourseSelectModel HNObjectValuesForKey:obj];
        [self.teacherModels addObject:model];
    }];
    [self addIsLastObject];
    [_teacherCollectionView reloadData];
    
    // 上课地点、地址
    self.proviceId = [dict[@"provinceid"] stringValue];
    self.cityId = [dict[@"cityid"] stringValue];
    self.areaId = [dict[@"areaid"] stringValue];
    [_regionBtn setTitle:[NSString stringWithFormat:@"%@%@%@", dict[@"provincename"], dict[@"cityname"], [self.areaId isEqualToString:@"0"] ? @"市辖区":dict[@"areaname"]] forState:_regionBtn.state];
    _address.text = [self JudgeNullClass:dict[@"address"]];
    
    // 评论模板
    [_commentBtn setTitle:[self JudgeNullClass:dict[@"templatename"]] forState:_commentBtn.state];
    self.commentId = [[self JudgeNullClass:dict[@"templateId"]] stringValue];
    
    // 售价、原价、详情
    _price.text = [NSString stringWithFormat:@"%.2f", [[self JudgeNullClass:dict[@"price"]] floatValue]];
    _showPrice.text = [NSString stringWithFormat:@"%.2f", [[self JudgeNullClass:dict[@"showPrice"]] floatValue]];
    _des.text = [self JudgeNullClass:dict[@"description"]];
    [self textViewDidChange:_des];
    
    
}

- (id)JudgeNullClass:(id)Obj {
    
    if (![Obj isKindOfClass:[NSNull class]]) {
        
        return Obj;
    } else {
        
        return nil;
        
    }
}

















#pragma mark - 加强课
- (void)strongCourseUI {
    
    
        HNThreeGoodEvaView *gv = [HNThreeGoodEvaView ConfigEvaViewWithDataArr:self.strongDatas CallBack:nil];
        [_threeGoodView addSubview:gv];
        [gv mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.equalTo(_threeGoodView.mas_top).offset(0);
            make.left.equalTo(_threeGoodView.mas_left).offset(0);
            make.right.equalTo(_threeGoodView.mas_right).offset(0);
            make.height.equalTo(@(44 + 30 * self.strongDatas.count));
        }];
    
        _threeGoodViewHeight.constant = 44 + 30 * self.strongDatas.count + 44;
    
    // 选择的数据
    [self.strongDatas enumerateObjectsUsingBlock:^(HNCourseListChartsModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        HNHandleCourseThreeGoodView *view = [[NSBundle mainBundle] loadNibNamed:[HNHandleCourseThreeGoodView description] owner:nil options:nil][0];
        view.model = obj;
        [_threeGoodView addSubview:view];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(_threeGoodView);
            make.height.equalTo(@30);
            make.top.equalTo(_threeGoodView.mas_top).offset(_threeGoodViewHeight.constant);
        }];
        
        _threeGoodViewHeight.constant += 30;
    }];
    _scrollViewHeight.constant += _threeGoodViewHeight.constant;
    [_scrollView layoutIfNeeded];

    
}






@end
